from flask import Blueprint, jsonify, request, g
import json
from loguru import logger
from app.err_no import errno_no
import traceback
from app.db import dbStallQuery
from app.db.mongoClient import MongoError

blueprint = Blueprint('stall_query', __name__, url_prefix='/api/stall')


@blueprint.route('/v1/query', methods=['POST'])
def stall_query():
    '''
    查询餐厅档口
    '''
    try:
        # 如果是档口管理员
        if g.userType == 'stall':
            j_data = json.loads(request.data)
            diningNo = j_data.get('diningNo')
            if diningNo is None or len(diningNo) <= 0 :
                return jsonify(errno_no.ErrServerParam.data(None))

            # 如果是档口管理员只能传一个餐厅号
            if len(diningNo) > 1:
                return jsonify(errno_no.ErrServerPermissionDenied.data(None))

            res = dbStallQuery.queryStall(diningNo, g.RelationStallNo)
            if res is False:
                return jsonify(errno_no.ErrServerDocumentNotExist.data(None))

            return jsonify(errno_no.OK.data({'stallList': res}))

        # 如果是超级管理员或者餐厅管理员
        j_data = json.loads(request.data)
        diningNo = j_data.get('diningNo')
        if diningNo is None or len(diningNo) <= 0 :
            return jsonify(errno_no.ErrServerParam.data(None))

        res = dbStallQuery.queryAllStall(diningNo)
        if res is False:
            return jsonify(errno_no.ErrServerDocumentNotExist.data(None))
            
        return jsonify(errno_no.OK.data({'stallList': res}))

    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('/v1/name_search', methods=['POST'])
def name_search():
    '''
    餐厅档口模糊搜索
    '''
    try:
        j_data = json.loads(request.data)
        diningNo = j_data.get('diningNo')
        stallName = j_data.get('stallName') # 档口名为空表示查询该餐厅下所有的档口
        
        if diningNo is None or len(diningNo) <= 0 \
            or stallName is None:
            return jsonify(errno_no.ErrServerParam.data(None))

        res = dbStallQuery.nameSearch(diningNo, stallName)
        if res is None:
            return jsonify(errno_no.ErrServerDocumentNotExist.data(None))

        return jsonify(errno_no.OK.data({"stallList": res}))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))